<?php

require_once("View/View/PageView.php");
require_once("Common/Model/commonThings.php");
require_once("Exercises/View/ExercisesView.php");
require_once("Exercises/Model/ExerciseModel.php");
require_once("login/src/Model/LoginValidation.php");

class ExersicesController
{
	/**
    *@var PageView
    **/
	private $pageView;
	/**
    *@var ExerciseModel
    **/
	private $exerciseModel;
	/**
    *@var ExersicesView
    **/
	private $exersicesView;
	/**
    *@var LoginValidation
    **/
	private $loginvalidation;

	public function __construct()
	{
		$this->pageView = new PageView();
		$this->exersicesView = new ExersicesView();
		$this->loginvalidation = new LoginValidation();
		$this->exerciseModel = new ExerciseModel();
	}	

	public function areWeLoggedIn()
	{
		if($this->loginvalidation->CheckIfWereLoggedIn() == false)
		{
			header("Location:index.php");
		}
	}

	/**
    *@return string html
    **/
	public function getPage()
	{ 
		$this->exerciseModel->resetErrorMessages();
		if($this->exersicesView->checkIfAddNewExercise())
		{					     
			$this->addOrEditNewExercise();
		}
		if($this->exersicesView->removeExerciseOnID())
		{
			$this->removeExercise(); 
		}
		if($this->exersicesView->editedExercise())
		{
			$this->addOrEditNewExercise(true); 
		}
		$html = $this->exersicesView->getExercisesPage();
		$html = $this->pageView->getHtmlPage("Övningar - Träningsdagboken", "", $html);
		return $html;
	}


	private function removeExercise()
	{
		$exerciseID = $this->exersicesView->getIdToRemove();
		$this->exerciseModel->ValidateAndDeleteExercise($exerciseID);
		header("Location:Exercises.php");
	}
  
	/**
    *@param bool
    **/
	private function addOrEditNewExercise($edit = false)
	{

		if(commonThings::checkIfPost())
		{
			$mouscleGroupID = $this->exersicesView->getNewMuscleGroupID();
			$eName = $this->exersicesView->getNewExerciseName();
			$eDescription = $this->exersicesView->getNewExerciseDescription();
			$youtubeLink =  $this->exersicesView->getNewYoutubeLink();
			$userID = $this->loginvalidation->getLoggedInUserID();

			if($this->exerciseModel->ValidateExercise($mouscleGroupID, $eName, $eDescription,$youtubeLink))
			{
				if($edit)
				{
					$exerciseID = $this->exerciseModel->getIdToEdit();
					$this->exerciseModel->CreateAndSaveExercise($mouscleGroupID, $eName, $eDescription,$youtubeLink, $userID,  $exerciseID);
				}
				else
				{
					$this->exerciseModel->CreateAndSaveExercise($mouscleGroupID, $eName, $eDescription,$youtubeLink, $userID);
				}
			}
		}
	}

}